package jhavelogger.server;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.BlockingQueue;

import jhavelogger.data.ConnectionFactory;
import jhavelogger.data.FakeIPLookup;
import jhavelogger.data.GeoIP;
import jhavelogger.data.JDBCLogDAO;
import jhavelogger.data.LogDAO;
import jhavelogger.models.DBLog;
import jhavelogger.models.JHaveLog;
import jhavelogger.visitor.DBLogVisitor;
import jhavelogger.visitor.DebuggingVisitor;
import jhavelogger.visitor.LogVisitor;

/**
 * A separate thread that handles committing parsed logs to the database.
 * @author Jared Schlicht
 */
public class DatabaseLoggingThread extends Thread {
    private LogVisitor visitor;
    private BlockingQueue<JHaveLog> logQueue;
    private Connection connection;
    
    /**
     * Constructs a new DatabaseLoggingThread
     * @param logQueue a threadsafe queue that contains parsed jhave log objects.
     */
    public DatabaseLoggingThread(BlockingQueue<JHaveLog> logQueue) {
	ConnectionFactory connectionFactory = new ConnectionFactory();
	try {
	    this.connection = connectionFactory.createConnection();
	} catch (Exception e) {
	    e.printStackTrace();
	    return;
	}
	
	this.visitor = new DBLogVisitor(new JDBCLogDAO(this.connection), new GeoIP());
	this.logQueue = logQueue;
    }
    
    @Override
    public void run() {
	if (this.connection == null) {
	    return;
	}
	
	while (true) {
	    try {
		JHaveLog log = this.logQueue.take();
		if (log == null) {
		    continue;
		}
		
		DBLog result = (DBLog)log.accept(this.visitor);
		if (result != null) {
		    // Print committed logs to the terminal
		    System.out.println(result.toString());
		}
	    } catch (InterruptedException e) {
		e.printStackTrace();
	    }
	}
    }
}
